<template>
    <view class="page" :style="{ '--color': color }">
        <status-bar :title="title ? title : '联系客服'"></status-bar>
        <view class="box">
            <!-- 布局 -->
            <view v-if="list && list.length > 0" class="catList" @click="showEmoji = false">
                <!-- 注释 -->
                <view class="DiLine" v-if="page > 1 && noMore">---------没有更多了---------</view>
                <view v-for="(item, key) in list" :key="key" class="item">
                    <view v-if="item.id == myID" class="right">
                        <view class="msg-box">
                            <view class="username">{{ item.username }}</view>
                            <!-- 图片 -->
                            <view class="img-box" v-if="item.content.indexOf('img[') > -1" @click="prevImg(item.content)">
                                <image @error="item.content = staticUrl + '/imageLoading.png'" :src="imgUrl + item.content.replace('img[', '').replace(']', '')" mode="widthFix"></image>
                            </view>
                            <!-- 表情 -->
                            <view class="face-box" v-else-if="item.content.indexOf('face[') > -1" v-html="rich(item.content)"></view>
                            <view class="message-box" v-else>{{ item.content }}</view>
                        </view>

                        <view style="margin-left: 10px">
                            <image class="avatar" @error="item.avatar = ''" :src="item.avatar ? item.avatar : staticUrl + '/youkeer.png'" />
                        </view>
                    </view>

                    <view v-else class="left">
                        <view>
                            <image class="avatar" @error="item.avatar = ''" :src="item.avatar ? item.avatar : staticUrl + '/youkeer.png'" />
                        </view>
                        <view class="msg-box">
                            <view class="username">{{ item.username }}</view>
                            <view class="img-box" v-if="item.content.indexOf('img[') > -1" @click="prevImg(item.content)">
                                <image :src="imgUrl + item.content.replace('img[', '').replace(']', '')" mode="widthFix"></image>
                            </view>
                            <!-- 有表情 -->
                            <view class="face-box" v-else-if="item.content.indexOf('face[') > -1" v-html="rich(item.content)"></view>
                            <view class="message-box" v-else>{{ item.content }}</view>

                            <view class="commodity" v-if="item.response && item.response[0].goods">
                                <view class="List" @click.stop="toUrl(`/pages/goods/goods_detail?goods_id=${sub.goods_id}`)" v-for="(sub, inx) in item.response[0].goods" :key="sub.goods_id">
                                    <image :src="$imgUrls(sub.img)" mode="aspectFill" class="Img"></image>
                                    <view class="box">
                                        <text class="title ellipsis_2">{{ sub.name }}</text>
                                        <text class="price color_ff4">￥{{ sub.price }}</text>
                                    </view>
                                </view>
                            </view>

                            <view class="Auxiliary" v-if="item.response && item.response.length > 1">
                                <view class="List" v-for="(sub, inx) in item.response.slice(1)" @click.stop="conversation(sub.content, sub)">
                                    {{ sub.content }}
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 输入框 -->
            <view class="bottom-box" :class="{ show1: showEmoji }">
                <view class="bottom">
                    <view class="bottom-p">
                        <view class="input-box">
                            <input type="text" confirm-type="send" @confirm="clickRequest" placeholder="请输入你要发送的内容" cursor-spacing="50" v-model="value" @focus="focus" />
                        </view>
                        <view class="thmeBg send-btn" @tap="clickRequest">发送</view>
                        <!-- <text class="iconfont icon-zengjia thmeColor" :style="{'--color': color}" @click="showEmoji = true"></text> -->
                    </view>

                    <!-- 底部分类 -->
                    <view class="classification">
                        <view @click="camera">
                            <image :src="staticUrl + '/icon/tupian.png'"></image>
                        </view>
                        <view @click="camera">
                            <image :src="staticUrl + '/icon/xiangji.png'"></image>
                        </view>
                        <view @click="show">
                            <image :src="staticUrl + '/icon/biaoqing.png'"></image>
                        </view>
                    </view>

                    <view class="emoji-box" :style="{ opacity: showEmoji ? 1 : 0 }">
                        <view class="title">表情</view>
                        <view class="emoji">
                            <image v-for="(fac, i) in face" :key="i" :src="staticUrl + '/face/' + fac + '.gif'" @click="checkEmoj(fac)"></image>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    import { mapState } from 'vuex';
    var ping = null,
        that;
    export default {
        data() {
            return {
                staticUrl: this.staticUrl,
                imgUrl: this.imgUrl,

                value: '',
                tableData: [],
                list: [],
                scrollTop: -1,
                myID: '', // 我
                mesage: {
                    type: 'chatMessage',
                    data: {
                        mine: {
                            username: '',
                            avatar: '',
                            id: '',
                            mine: true,
                            content: ''
                        },
                        to: {
                            username: '',
                            id: '',
                            avatar: '',
                            sign: '',
                            status: '',
                            name: '',
                            type: 'friend'
                        },
                        token: ''
                    }
                },
                start: true,
                hisID: '',
                page: 1,
                showEmoji: false, // 显示表情
                socketTask: null,
                face: [
                    '微笑',
                    '嘻嘻',
                    '哈哈',
                    '可爱',
                    '可怜',
                    '挖鼻',
                    '吃惊',
                    '害羞',
                    '挤眼',
                    '闭嘴',
                    '鄙视',
                    '爱你',
                    '泪',
                    '偷笑',
                    '亲亲',
                    '生病',
                    '太开心',
                    '白眼',
                    '右哼哼',
                    '左哼哼',
                    '嘘',
                    '衰',
                    '委屈',
                    '吐',
                    '哈欠',
                    '抱抱',
                    '怒',
                    '疑问',
                    '馋嘴',
                    '拜拜',
                    '思考',
                    '汗',
                    '困',
                    '睡',
                    '钱',
                    '失望',
                    '酷',
                    '色',
                    '哼',
                    '鼓掌',
                    '晕',
                    '悲伤',
                    '抓狂',
                    '黑线',
                    '阴险',
                    '怒骂',
                    '互粉',
                    '心',
                    '伤心',
                    '猪头',
                    '熊猫',
                    '兔子',
                    'ok',
                    '耶',
                    'good',
                    'NO',
                    '赞',
                    '来',
                    '弱',
                    '草泥马',
                    '神马',
                    '囧',
                    '浮云',
                    '给力',
                    '围观',
                    '威武',
                    '奥特曼',
                    '礼物',
                    '钟',
                    '话筒',
                    '蜡烛',
                    '蛋糕'
                ],
                httpUrl: this.echatUrl,
                more: false,
                shop_id: 0,
                pageNum: 20,

                noMore: false,
                title: '联系客服',
                chat: 'chat',
                type: 'answer'
                // title: uni.getStorageSync('startUp').title
            };
        },
        onLoad(e) {
            that = this;
            if (e.shop_id) {
                that.shop_id = e.shop_id;
            }
            this.closeSocket();
            this.conversation();
            // this.connectSocketInit();
            this.$nextTick(() => {
                setTimeout(() => {
                    that.goBottom();
                }, 1000);
            });
        },

        methods: {
            conversation(content) {
                this.$showLoading('');
                if (content && this.myID) {
                    this.mesage.data.mine.content = content;
                    this.list.push(this.mesage.data.mine);
                }
                this.$http
                    .post({
                        url: 'https://api.mogoie.com/api/v1/coze/conversation',
                        data: {
                            type: this.chat,
                            content: content ? content : this.value
                        }
                    })
                    .then((res) => {
                        this.$hideLoading();
                        if (res.status != 200) return this.$Toast(res.msg);

                        const result = res.data;
                        const response = result.response;
                        if (response[0].type == 'convert') {
                            this.type = 'convert';
                            this.connectSocketInit();
                            return;
                        }
                        console.log(1000);
                        this.myID = result.mine.id;
                        // this.mesage.data.mine = result.mine;
                        // this.mesage.data.to = result.to;

                        this.mesage.data = {
                            mine: {
                                username: result.mine.nickname,
                                avatar: result.mine.avatar,
                                id: result.mine.id,
                                mine: true,
                                content: ''
                            },
                            to: {
                                username: result.to.nickname,
                                id: result.to.id,
                                avatar: result.to.avatar,
                                sign: result.to.sign,
                                status: result.to.status,
                                name: result.to.name,
                                type: 'friend'
                            }
                        };

                        result.to.content = response[0].content;
                        result.to.response = response;
                        this.list.push(result.to);
                    });
            },
            connectSocketInit() {
                that.$http
                    .get({
                        url: '/singleSaleApi/getChatToken',
                        data: {
                            shop_id: that.shop_id // 0：联系总平台 其他：联系店铺
                        }
                    })
                    .then((res1) => {
                        if (res1.code != 200) return this.$Toast(res1.msg);
                        that.myID = res1.data.mine.id;
                        // that.mesage.data.mine = res1.data.mine;
                        // that.mesage.data.to = res1.data.to;
                        // that.mesage.data.token = res1.data.token;
                        that.mesage.data = {
                            mine: {
                                username: res1.data.mine.nickname,
                                avatar: res1.data.mine.avatar,
                                id: res1.data.mine.id,
                                mine: true,
                                content: ''
                            },
                            to: {
                                username: res1.data.to.nickname,
                                id: res1.data.to.id,
                                avatar: res1.data.to.avatar,
                                sign: res1.data.to.sign,
                                status: res1.data.to.status,
                                name: res1.data.to.name,
                                type: 'friend'
                            },
                            token: res1.data.token
                        };
                        that.token = res1.data.token;
                        that.hisID = res1.data.to.id;
                        that.myname = res1.data.mine.nickname;
                        let server = res1.data.server;
                        if (res1.store_name) that.title = res1.store_name;
                        that.socketTask = uni.connectSocket({
                            url: server + '//?token=' + res1.data.token,
                            header: {
                                'content-type': 'application/json'
                            },
                            method: 'GET',
                            success() {
                                uni.onSocketOpen(function (res) {
                                    // Socket连接已打开！
                                    that.getChatLog('rev');
                                    that.goBottom();
                                    uni.sendSocketMessage({
                                        data: 'ok',
                                        success: function () {
                                            uni.onSocketMessage(function (res1) {
                                                var ret = JSON.parse(res1.data);
                                                console.log('*******onSocketMessage*******');
                                                console.log(ret);
                                                if (ret.content && ret.offline != 1) {
                                                    // 离线消息不push 不然消息记录重复
                                                    that.list.push(ret);
                                                    console.log(that.list, 'this.list');
                                                    that.goBottom();
                                                }
                                            });
                                        }
                                    });
                                    ping = setInterval(function () {
                                        that.socketTask.send({
                                            data: 'ping',
                                            async success(back) {
                                                console.log('ping');
                                            }
                                        });
                                    }, 1000 * 10);
                                });
                            },
                            fail(res2) {
                                console.log(res2);
                            }
                        });
                    });
            },
            goBottom() {
                setTimeout(() => {
                    uni.pageScrollTo({
                        duration: 0,
                        scrollTop: 999999999
                    });
                }, 200);
            },
            getChatLog(type) {
                // 获取历史
                that.more = false;
                that.noMore = false;
                uni.request({
                    url: that.httpUrl + '/echat/User/chatLog',
                    method: 'POST',
                    data: {
                        token: that.token,
                        page: that.page,
                        limit: that.pageNum,
                        id: that.hisID // 对方id
                    },
                    dataType: 'json',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    success: function (res) {
                        if (res.data.code == 0) {
                            let list = res.data.data.data;
                            list.forEach((item) => {
                                if (item.is_ai == 1) {
                                    item.response = item.content;
                                    item.content = item.response[0].content;
                                }
                            });
                            if (list) {
                                if (type == 'rev') {
                                    // 反序
                                    that.list = that.list.concat(list).reverse();
                                }
                                if (type == 'des') {
                                    // 正序.reverse()
                                    that.list = list.concat(that.list);
                                    that.$nextTick(function () {
                                        uni.createSelectorQuery()
                                            .in(this)
                                            .select('.box')
                                            .boundingClientRect(function (data) {
                                                uni.pageScrollTo({
                                                    duration: 0,
                                                    scrollTop: data.height - that.scrollTop
                                                });
                                            })
                                            .exec();
                                    });
                                }
                                if (list.length > that.pageNum - 1) {
                                    that.more = true;
                                    that.page++;
                                }
                            }
                            if ((!list || list.length < that.pageNum) && that.page > 1) {
                                that.noMore = true;
                            }
                        } else {
                            uni.showToast({
                                icon: 'none',
                                title: res.data.msg,
                                duration: 2000
                            });
                        }
                    }
                });
            },

            clickRequest() {
                // 发送
                if (!this.value) return this.$Toast('不能发送空白消息');
                if (this.type == 'answer') {
                    this.conversation(this.value);
                    this.value = '';
                    return;
                }
                let temp = this.mesage;
                temp.data.mine['content'] = this.value;
                var ok = JSON.stringify(temp);
                this.socketTask.send({
                    data: ok,
                    async success() {
                        console.log('消息发送成功');
                        let mine = {
                            username: that.mesage.data.mine.username,
                            avatar: that.mesage.data.mine.avatar,
                            id: that.mesage.data.mine.id,
                            mine: true,
                            content: that.value
                        };
                        that.list.push(mine);
                        console.log(that.list, 'this.list');
                        that.value = '';
                        that.goBottom();
                        that.socketTask.onMessage((res) => {
                            console.log('收到服务器内容：' + res.data);
                            that.goBottom();
                        });
                    }
                });
            },
            checkEmoj(emoji) {
                emoji = 'face[' + emoji + '] ';
                that.value += emoji;
            },
            focus() {
                that.showEmoji = false;
                that.goBottom();
            },
            show() {
                that.goBottom();
                that.showEmoji = true;
            },
            closeSocket() {
                uni.closeSocket(function (res) {
                    console.log('WebSocket 已关闭！');
                });
            },
            camera() {
                var _self = this;
                uni.chooseImage({
                    count: 1, //默认9
                    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['camera', 'album'],
                    success: function (res) {
                        uni.showLoading({
                            title: ''
                        });
                        const uploadTask = uni.uploadFile({
                            url: _self.baseUrl + '/zzjApp/uploadChatPic?bid=' + that.bid,
                            filePath: res.tempFilePaths[0],
                            name: 'file',
                            dataType: 'json',
                            success: function (uploadFileRes) {
                                uploadFileRes = JSON.parse(uploadFileRes.data);
                                let ok = _self.mesage;
                                ok.data.mine['content'] = 'img[' + uploadFileRes.data.src + ']';
                                _self.socketTask.send({
                                    data: JSON.stringify(ok),
                                    async success() {
                                        console.log('消息发送成功');
                                        let mine = {
                                            username: that.mesage.data.mine.username,
                                            avatar: that.mesage.data.mine.avatar,
                                            id: that.mesage.data.mine.id,
                                            mine: true,
                                            content: 'img[' + uploadFileRes.data.src + ']'
                                        };
                                        _self.list.push(mine);
                                        that.goBottom();
                                    }
                                });
                            },
                            fail: function (res) {
                                uni.showToast({
                                    title: res.msg,
                                    icon: 'none'
                                });
                            },
                            complete: function () {
                                uni.hideLoading();
                            }
                        });
                    }
                });
            },
            prevImg(img) {
                var arry = this.imgUrl + img.replace('img[', '').replace(']', '');
                uni.previewImage({
                    urls: [arry]
                });
            }
        },
        computed: {
            ...mapState(['tabTitle', 'color', 'city', 'navHeight', 'System', 'vid', 'share', 'bid']),
            rich(text) {
                return function (text) {
                    var reg = /face\[([^\[\]])*\]/g;
                    var des = text.replace(reg, (ev) => {
                        ev = ev.replace('face[', '').replace(']', '');
                        ev =
                            "<span style='margin: 3px 0;width:22px;height:22px;display:inline-block;background:url(" +
                            this.staticUrl +
                            '/face/' +
                            ev +
                            ".gif);background-size: contain;vertical-align: middle;'></span>";
                        return ' ' + ev + ' ';
                    });
                    return des;
                };
            },
            valueFilter(text) {
                return function (text) {
                    var reg = /face\[([^\[\]])*\]/g;
                    var des = text.replace(reg, (ev) => {
                        ev = ev.replace('face', '');
                        return ev;
                    });
                    return des;
                };
            }
        },
        onPageScroll(e) {
            if (e.scrollTop == 0 && this.more) {
                uni.createSelectorQuery()
                    .in(this)
                    .select('.box')
                    .boundingClientRect(function (data) {
                        that.scrollTop = data.height;
                        that.getChatLog('des');
                    })
                    .exec();
            }
        },
        onUnload() {
            this.closeSocket();
        },
        beforeDestroy() {
            // 关闭socket
            this.closeSocket();
        }
    };
</script>

<style lang="scss" scoped>
    .page {
        background-color: #ffffff;
        .box {
            .catList {
                box-sizing: border-box;
                padding: 0 20rpx;
                .item {
                    padding-bottom: 30rpx;
                    padding-top: 10rpx;
                    .username {
                        font-size: 26rpx;
                        color: #999;
                    }
                    .avatar {
                        width: 80rpx;
                        height: 80rpx;
                        border-radius: 50%;
                        border: 1px solid #dddddd;
                    }
                    .message-box {
                        border: 1px solid #eeeeee;
                        font-size: 26rpx;
                        color: #232323;
                        border-radius: 14rpx;
                        margin-top: 10rpx;
                        text-align: justify;
                        padding: 10rpx 16rpx;
                        display: inline-block;
                    }
                    .img-box {
                        border: 1px solid #eeeeee;
                        margin-top: 10rpx;
                        display: inline-block;
                        border-radius: 14rpx;
                        overflow: hidden;
                        image {
                            display: block;
                            width: 300rpx;
                        }
                    }
                    .face-box {
                        border: 1px solid #eeeeee;
                        border-radius: 14rpx;
                        margin-top: 10rpx;
                        padding: 10rpx 16rpx;
                        display: inline-block;
                        image {
                            display: inline-block;
                            width: 44rpx;
                            height: 44rpx;
                            margin: 0 6rpx 6rpx;
                        }
                    }
                    .msg-box {
                        max-width: 70%;
                    }
                    .left {
                        display: flex;
                        flex-wrap: nowrap;
                        justify-content: flex-start;
                        text-align: left;
                        .message-box,
                        .face-box {
                            background: #f8f8f8;
                        }
                        .msg-box {
                            margin-left: 10px;
                            .commodity {
                                width: 100%;
                                border: 1px solid red;
                                display: flex;
                                flex-direction: column;
                                border: 1px solid #d5d9e3;
                                padding: 10rpx;
                                border-radius: 10rpx;
                                margin-top: 10rpx;
                                .List {
                                    width: 100%;
                                    display: flex;
                                    align-items: center;
                                    margin-bottom: 20rpx;
                                    .Img {
                                        width: 120rpx;
                                        height: 120rpx;
                                        border-radius: 10rpx;
                                        margin-right: 14rpx;
                                    }
                                    .box {
                                        flex: 1;
                                        height: 120rpx;
                                        display: flex;
                                        flex-direction: column;
                                        justify-content: space-between;
                                        .title {
                                            color: #999;
                                            font-size: 22rpx;
                                        }
                                        .price {
                                            font-size: 22rpx;
                                        }
                                    }
                                }
                            }

                            .Auxiliary {
                                width: 100%;
                                margin-top: 10rpx;
                                display: flex;
                                flex-direction: column;
                                align-items: flex-start;
                                .List {
                                    display: inline-block;
                                    border: 1px solid #d5d9e3;
                                    padding: 10rpx 20rpx;
                                    border-radius: 10rpx;
                                    font-size: 22rpx;
                                    color: #666;
                                    margin-bottom: 10rpx;
                                }
                                .List:last-child {
                                    margin-bottom: 0;
                                }
                            }
                        }
                    }
                    .right {
                        display: flex;
                        flex-wrap: nowrap;
                        justify-content: flex-end;
                        text-align: right;
                        .message-box,
                        .face-box {
                            background: #b0e5ff96;
                        }
                    }
                }
            }
            .bottom-box {
                height: 188rpx;
                box-sizing: content-box;
                padding-bottom: constant(safe-area-inset-bottom);
                padding-bottom: env(safe-area-inset-bottom);
                &.show1 {
                    height: 610rpx;
                    .bottom {
                        height: 600rpx;
                    }
                }
                .bottom {
                    width: 100%;
                    background: #f1f1f1;
                    padding-top: 10px;
                    position: fixed;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    height: 174rpx;
                    transition: all 0.2s;
                    box-sizing: content-box;
                    padding-bottom: constant(safe-area-inset-bottom);
                    padding-bottom: env(safe-area-inset-bottom);
                    .bottom-p {
                        height: 74rpx;
                        display: flex;
                        flex-wrap: nowrap;
                        padding: 0 20rpx;
                        .icon-zengjia {
                            font-size: 64rpx;
                            padding-left: 20rpx;
                        }
                        .input-box {
                            flex: 1;
                            height: 100%;
                            background-color: #ffffff;
                            border-radius: 40px;
                            display: flex;
                            input {
                                flex: 1;
                                height: 100%;
                                padding: 0 20rpx !important;
                            }
                        }
                        .send-btn {
                            width: 146rpx;
                            font-size: 28rpx;
                            text-align: center;
                            line-height: 74rpx;
                            border-radius: 40px;
                            color: #ffffff;
                            background: #25b0f3;
                            margin-left: 20rpx;
                        }
                    }
                    .classification {
                        display: flex;
                        flex-wrap: nowrap;
                        margin: 0 auto;
                        overflow: hidden;
                        view {
                            height: 100%;
                            height: 78rpx;
                            padding: 0 20rpx;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            image {
                                width: 40rpx;
                                height: 40rpx;
                            }
                        }
                    }
                    .emoji-box {
                        position: relative;
                        z-index: 2;
                        .title {
                            padding: 0 20rpx;
                        }
                        .emoji {
                            padding: 10rpx 0;
                            height: 396rpx;
                            box-sizing: border-box;
                            overflow-y: auto;
                            image {
                                margin: 12rpx 0 12rpx 22rpx;
                                width: 44rpx;
                                height: 44rpx;
                            }
                        }
                    }
                }
            }
        }
    }
</style>
